var express = require('express');
var router = express.Router();
const { userModel } = require("../module/module")
const UniSMS = require('unisms').default
const { encrypt, decrypt } = require("./aes")
const { getlongTerm, getshortTerm } = require("./token")
const nodemailer = require('nodemailer')
const {WebSocketServer}= require('ws')
const app = express()
app.use(express.json())


//存放数据结构
const connection = {}

const server = app.listen(3000)
const wss = new WebSocketServer({ server })

wss.on('connection', (ws) => {
  console.log('链接已建立');
    ws.on('message', (message) => {
        const data = JSON.parse(message)
        
        if (data.action === 'login') {
            if (connection[data.id] && connection[data.id].fingerprint) {
                //提示旧设备
                connection[data.id].socket.send(JSON.stringify({
                    action:'logout',
                    msg:`你的账号于${new Date().toLocaleString()}在别的设备登录，如非本人操作，建议尽快修改密码以免造成信息泄露或资产损失！` 
                }))
                connection[data.id].socket.close() //断开旧设备连接
                connection[data.id].socket = ws //更新ws
            } else {
                connection[data.id] = {
                    socket: ws, //记录ws
                    fingerprint: data.fingerprint //记录指纹
                }
            }
        }
    })
})


//短信头部
const client = new UniSMS({
  accessKeyId: 'Pz5fPWY17kd5YgEmRtCnMd59oxERg9i28vx3x1PAJeRPMRTrs'  // AccessKeyID
})
const SmsSignature = '吉世旺'

async function sendSMS(mobile, template, codeNumber) {
  try {
    const data = await client.send({
      to: mobile,  //手机号
      signature: SmsSignature, //你的短信签名 名称
      templateId: template,  //你的短信签名模版
      templateData: { code: codeNumber } //短信验证码
    })
    return data
  } catch (error) {
    console.error('Error sending SMS:', error)
    throw error
  }
}

// 生成指定位数的随机数
function generateRandomCode(length) {
  const min = Math.pow(10, length - 1)
  const max = Math.pow(10, length) - 1
  return Math.floor(Math.random() * (max - min + 1) + min).toString()
}

// 短信验证码路由
router.get('/Test/MobileCodeNumber', async (req, res) => {
  if (!req.query.phone)
    res.send({ code: 400, msg: 'phone参数必传' })
  try {
    const mobileNumber = req.query.phone // 替换为实际的手机号码
    const verificationCode = generateRandomCode(6) // 生成或获取实际的验证码
    const TemplateContent = 'pub_verif_ttl3' // 短信模板码
    await sendSMS(mobileNumber, TemplateContent, verificationCode)
    res.send({ code: 200, msg: '验证码已发送', rightcode: verificationCode })
  } catch (error) {
    console.error(error)
    res.send({ code: 400, msg: '验证码发送失败' })
  }
})

// 注册路由
router.post("/register", async (req, res) => {
  let body = req.body
  let user = await userModel.find({ tel: body.tel })
  if (user.length > 0) {
    res.send({
      code: 201,
      msg: "该手机号已注册"
    })
  } else {
    body.password = encrypt(body.password)
    userModel.create(body)
    res.send({
      code: 200,
      msg: "注册成功"
    })
  }
})

// 登录路由
router.post("/login", async (req, res) => {
  let { phone, password } = req.body;

  let user = await userModel.find({ tel: phone })
  if (user.length === 0) {
    res.send({
      code: 201,
      msg: "该手机号未注册"
    })
  } else {
    if (password == decrypt(user[0].password)) {
      res.send({
        code: 200,
        msg: "登录成功",
        longtermToken: getlongTerm(),
        shorttermToken: getshortTerm(),
        user: user[0]
      })
    } else {
      res.send({
        code: 201,
        msg: "密码错误"
      })
    }
  }
})


// 随机产生六位验证码
function createSixNum() {
  let Num = "";
  for (var i = 0; i < 6; i++) {
    Num += Math.floor(Math.random() * 10);
  }
  return Num;
}

// 创建一个SMTP客户端对象
let transporter = nodemailer.createTransport({
  host: "smtp.qq.com", // 发送方邮箱 qq 通过lib/wel-konw
  port: 587,
  secure: false, // true for 465, false for other ports
  requireTLS: true, // 对于端口587，使用true
  auth: {
    user: '3072320492@qq.com', // 发送方邮箱地址
    pass: 'rrcnmwakexlldhdb'  // mtp 验证码 这个有了才可以发送邮件，可以qq邮箱去查看自己的码
    
  }
})


//邮件格式
function send(mail, code) {
  const mailContent = `
  <p>尊敬的用户:</p>
  <p>您好！</p>
  <p>陌小欷的盲盒为您提供了以下验证码，用于完成您的操作：</p>
  <p><span style="font-weight: bold; color: #DC143C;">${code}</span></p>
  <p>请注意，此验证码的有效期为5分钟。</p>
  <p>感谢您的使用和支持！</p>
  <p>祝您一天愉快！</p>
  `;
  // 邮件信息
  let mailobj = {
    from: '<3072320492@qq.com>', // 发送方地址自定义
    to: mail, // 接收方地址
    subject: "注册验证码", // 主题内容
    html: mailContent // 使用html属性设置HTML内容
  }
  return new Promise((reslove, reject) => {
    // 发送邮件
    transporter.sendMail(mailobj, (err, data) => {
      if (err) {
        reject()
      } else {
        reslove()
      }
    })
  })
}


//发送邮件
router.get('/getemail', async (req, res) => {
  try {
    const { mail } = req.query; //获取前端传过来的邮箱
    let data = await userModel.find({ email: mail })
    if (data.length > 0) { 
      const NodeCache = require("node-cache");
    const myCache = new NodeCache();

    let code = createSixNum(); // 随机生成6位验证码
    // 将code存入缓存
    myCache.set("code", code, 300); // 缓存5分钟
    send(mail, code)  //发送邮件的函数,传入邮箱和6位验证码
      .then(() => {
        console.log(`验证码发送成功`);
        res.json({ msg: '验证码发送成功', code:200, data: code });
      })
      .catch((err) => {
        console.error(err, '邮件发送失败11111');
        res.json({ msg: '验证码发送失败' });
      });
     }else{
      res.json({ msg: '该邮箱未注册', code:201 });
     }
    
  } catch (error) {
    console.error(error, '邮件发送失败22222');
    res.status(500).json({ message: '邮件发送失败' });
  }
});

//忘记密码
router.put('/updatepassword',async (req,res)=>{
  if(req.body.phone!=''){
    await userModel.updateOne({tel:req.body.phone},{password:encrypt(req.body.password)})
  }else{
    await userModel.updateOne({email:req.body.email},{password:encrypt(req.body.password)})
  }
  res.json({msg:'修改成功',code:200})
})

module.exports = router;
